﻿using Datav.Design;
using Datav.Design.Datas.Ticket;
using Datav.Design.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Zdap.Common;
using Zdap.Common.API.Extensions;

namespace Datav.Web.Api.Controllers
{
    /// <summary>
    /// 账号登录
    /// </summary>
    [AllowAnonymous]
    public class OAuthController : BaseController
    {
        private IProjectUserService _service;
        private ICaptchaService _captchaService;
        private SigningCredentials _signingCredentials;

        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceFactory"></param>
        /// <param name="service"></param>
        /// <param name="signingCredentials"></param>
        public OAuthController(IServiceFactory serviceFactory, IProjectUserService service, SigningCredentials signingCredentials) : base(serviceFactory)
        {
            _signingCredentials = signingCredentials;
            _service = serviceFactory.Resolve<IProjectUserService>();
            _captchaService = serviceFactory.Resolve<ICaptchaService>();
        }

        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <param name="type">验证码类型（0-普通验证码 1-算数计算验证码）</param>
        /// <param name="width">验证码图片宽度</param>
        /// <param name="height">验证码图片高度</param>
        /// <param name="length">验证码字符个数</param>
        /// <param name="pid">验证码唯一ID（由服务端雪花算法生成并返回，验证的时候传回服务端）</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult GetVerifyCode(CaptchaType type = CaptchaType.Normal, int width = 120, int height = 30, int length = 4, long pid = 0)
        {
            var captchaResult = _captchaService.GetVerifyCode(type, width, height, length, pid);
            //return File(captchaResult.CaptchaBytes, "image/png");
            return Ok(new ResponseContext<object>(new
            {
                captchaResult.Id,
                Data = captchaResult.Base64Data
            }));
        }

        /// <summary>
        /// 学生用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous, HttpPost]
        public async ValueTask<ResponseContext<UserTicket>> Login(LoginDto dto)
        {
            ResponseContext<UserTicket> response = new ResponseContext<UserTicket>();
            //var (success, msg) = _captchaService.Validate(dto.VerifyCodeId, dto.VerifyCode);
            //if (!success)
            //{
            //    return response.SetError(msg);
            //}
            //else
            {
                response = await _service.Login(dto, HttpContext.GetClientUserIp());
                if (response.Code == CommonConstants.SuccessCode)
                {
                    string field = $"{response.Data.Id}-{response.Data.LoginType}";
                    var token = UserTicketHelper.BuildJwtToken(response.Data);
                    await RedisHelper.SetAsync($"{CacheKeys.UserLoginTokenHashKey}:{response.Data.Id}", token, 60 * 24 * 60);
                    response.Data.AccessToken = token;
                }
            }
            return response;
        }

        /// 增加登陆验证码
        /// </summary>
        /// <returns></returns>
        //[AllowAnonymous, HttpGet, Route("getVierificationCode"),]
        //public async Task<ResponseContext<VierificationCodeDto>> GetVierificationCode()
        //{
        //    var result = new ResponseContext<VierificationCodeDto> { Code = CommonConstants.BadRequest, Msg = "" };
        //    string code = VierificationCode.RandomText();
        //    var data = new VierificationCodeDto
        //    {
        //        Img = VierificationCode.CreateBase64Imgage(code),
        //        Uuid = Guid.NewGuid().ToString()
        //    };
        //    await RedisHelper.SetAsync(CacheKeys.VierificationCodeHashKey + data.Uuid.ToString(), code, new TimeSpan(0, 5, 0));
        //    result.Data = data;
        //    result.Code = CommonConstants.SuccessCode;
        //    return result;

        //}

        /// <summary>
        /// 用户登录token
        /// </summary>
        /// <param name="id"></param>
        /// <param name="loginType"></param>
        /// <returns></returns>
        //[AllowAnonymous, HttpGet]
        //public async Task<ResponseContext<Zdap.Common.UserTicket>> GetToken(long id, int loginType)
        //{
        //    ResponseContext<Zdap.Common.UserTicket> response = new ResponseContext<Zdap.Common.UserTicket>();
        //    if (response.Code == CommonConstants.SuccessCode)
        //    {
        //        var cacheToken = RedisHelper.HGet(CommonRedisCache.UserLoginTokenHashKey, $"{id}-{loginType}");
        //        var data = new Zdap.Common.UserTicket
        //        {
        //            Id = id,
        //            LoginType = loginType,
        //            AccessToken = cacheToken
        //        };
        //        response.Data = data;
        //        response.Code = CommonConstants.SuccessCode;
        //    }
        //    return response;
        //}
    }
}